package com.crocodileQ.service.impl;

import com.crocodileQ.common.AppException;
import com.crocodileQ.common.R;
import com.crocodileQ.enums.AppExceptionMsgEnum;
import com.crocodileQ.service.UploadService;

import com.crocodileQ.utils.PathUtils;
import com.crocodileQ.utils.QiNiuOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private QiNiuOssUtil qiNiuOssUtil;

    /**
     * 上传图片
     * @param img
     * @return
     */
    public R uploadImg(MultipartFile img) {

        byte[] bytes = null;
        try {
            bytes = img.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = img.getOriginalFilename();
        //处理文件空情况
        if(!StringUtils.hasText(filename)){
            throw new AppException(AppExceptionMsgEnum.FILENAME_ERROR);
        }

        //判断文件类型（jpe、png）
        if(!filename.endsWith(".png")&&!filename.endsWith(".jpg")){
            throw new AppException(AppExceptionMsgEnum.FILENAME_ERROR);
        }

        //生成新文件名
        String newFileName = PathUtils.generateFilePath(filename);

        String url = qiNiuOssUtil.upload(bytes, newFileName);

        return R.success(url);
    }
}
